package com.enba.boot.security.jwt;

import com.enba.boot.core.base.Result;
import com.enba.boot.security.enums.AuthStatusEnum;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

/** 认证失败处理器 */
public class DefaultJwtAuthenticationFailureHandler implements AuthenticationFailureHandler {
  @Override
  public void onAuthenticationFailure(
      HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
      throws IOException {
    AuthStatusEnum status = AuthStatusEnum.AUTHENTICATION_FAILURE;
    if (e instanceof UsernameNotFoundException) {
      status = AuthStatusEnum.USERNAME_NOT_FOUND;
    } else if (e instanceof BadCredentialsException) {
      status = AuthStatusEnum.BAD_CREDENTIALS;
    } else if (e instanceof DisabledException) {
      status = AuthStatusEnum.ACCOUNT_DISABLED;
    } else if (e instanceof AccountExpiredException) {
      status = AuthStatusEnum.ACCOUNT_EXPIRED;
    } else if (e instanceof LockedException) {
      status = AuthStatusEnum.ACCOUNT_LOCKED;
    } else if (e instanceof CredentialsExpiredException) {
      status = AuthStatusEnum.CREDENTIALS_EXPIRED;
    }
    Result.render(response, Result.err(status.getCode(), status.getMsg()));
  }
}
